package com.jarchie.greendao;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.jarchie.greendao.adapter.UserAdapter;
import com.jarchie.greendao.entity.User;
import com.jarchie.greendao.gen.UserDao;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private RecyclerView mRecyclerView;
    private EditText mEditName;
    private Button mBtnAdd,mBtnDelete,mBtnUpdate,mBtnQuery;
    private List<User> mUserList = new ArrayList<>();
    private UserAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        initData();
    }

    //初始化数据
    private void initData() {
        mUserList = GreenDaoManager.getInstance().getDaoSession().getUserDao().queryBuilder().build().list();
        mAdapter = new UserAdapter(this, mUserList);
        mRecyclerView.setAdapter(mAdapter);
    }

    //初始化监听事件
    private void initListener() {
        mBtnAdd.setOnClickListener(this);
        mBtnDelete.setOnClickListener(this);
        mBtnUpdate.setOnClickListener(this);
        mBtnQuery.setOnClickListener(this);
    }

    //初始化View
    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.user_list);
        mEditName = (EditText) findViewById(R.id.edit_name);
        mBtnAdd = (Button) findViewById(R.id.btn_add);
        mBtnDelete = (Button) findViewById(R.id.btn_delete);
        mBtnUpdate = (Button) findViewById(R.id.btn_update);
        mBtnQuery = (Button) findViewById(R.id.btn_query);
        //创建默认的线性LayoutManager
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        mRecyclerView.setHasFixedSize(true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_add:
                insertUser(null, mEditName.getText().toString(),"18");
                break;
            case R.id.btn_delete:
                deleteUser(mEditName.getText().toString());
                break;
            case R.id.btn_update:
                updateUser("张三","张大大");
                break;
            case R.id.btn_query:
                queryUser();
                break;
        }
    }

    /**
     * 查询数据
     */
    private void queryUser(){
        UserDao userDao = GreenDaoManager.getInstance().getDaoSession().getUserDao();
        List<User> list = userDao.queryBuilder()
                .where(UserDao.Properties.Id.notEq(999))
                .orderDesc(UserDao.Properties.Id)
                .limit(3)
                .build().list();
        mUserList.clear();
        mUserList.addAll(list);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 根据名字更新某条数据的名字
     */
    private void updateUser(String prevName, String newName) {
        UserDao userDao = GreenDaoManager.getInstance().getDaoSession().getUserDao();
        User findUser = userDao.queryBuilder().where(UserDao.Properties.Name.eq(prevName)).build().unique();
        if (findUser != null) {
            findUser.setName(newName);
            GreenDaoManager.getInstance().getDaoSession().getUserDao().update(findUser);
            Toast.makeText(MyApplication.getContext(), "修改成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MyApplication.getContext(), "用户不存在", Toast.LENGTH_SHORT).show();
        }
        mUserList.clear();
        mUserList.addAll(userDao.queryBuilder().build().list());
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 根据名字删除某个用户
     */
    private void deleteUser(String name) {
        UserDao userDao = GreenDaoManager.getInstance().getDaoSession().getUserDao();
        User findUser = userDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().unique();
        if (findUser != null) {
            userDao.deleteByKey(findUser.getId());
        }
        mEditName.setText("");
        mUserList.clear();
        mUserList.addAll(userDao.queryBuilder().build().list());
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 向本地数据库里添加数据
     */
    private void insertUser(Long id, String name,String age) {
        UserDao userDao = GreenDaoManager.getInstance().getDaoSession().getUserDao();
        User user = new User(id, name,age);
        userDao.insert(user);
        mEditName.setText("");

        mUserList.clear();
        mUserList.addAll(userDao.queryBuilder().build().list());
        mAdapter.notifyDataSetChanged();
    }

}
